clear all;
close all;
clc;

% Initialization

v = [0.5 0 0.5]'; % Initial vector [x y z]'
m = 0; %-1 0 1
mode = 0; % 1==A->0, 0==z->0
I = 40; %Repititions

% Generate Fi, alphai and K

if (m == 1)
	Fi = 0 : (I - 1);
	alphai = atan(2 .^ (-1 .* Fi));
	K = prod(1 ./ sqrt(1 + 2 .^ (-2 .* Fi)));
elseif (m == 0)
	Fi = 1 : I;
	alphai = 2 .^ (-1 .* Fi);
	K = 1;
elseif (m == -1)
	Fi = zeros(1, I);
	Fi_rep = 4;
	Fi_last = 0;
	for i = 1 : I
		if (Fi_last == Fi_rep)
			Fi(i) = Fi_rep;
			Fi_rep = 3 * Fi_rep + 1;
		else
			Fi(i) = Fi_last + 1;
		endif
		Fi_last = Fi(i);
	endfor
	clear Fi_rep;
	clear Fi_last;
	clear i;
	alphai = atanh(2 .^ (-1 .* Fi));
	K = prod(1 ./ sqrt(1 - 2 .^ (-2 .* Fi)));
endif

% Main loop
for i = 1 : I
	if (((v(2) >= 0) && (mode == 1)) || ((v(3) < 0) && (mode == 0)))
		v_update(1) = v(1) + m .* v(2) .* 2 .^ (-1 .* Fi(i));
		v_update(2) = v(2) - v(1) .* 2 .^ (-1 .* Fi(i));
		v_update(3) = v(3) + alphai(i);
		v(1) = v_update(1);
		v(2) = v_update(2);
		v(3) = v_update(3);
	else
		v_update(1) = v(1) - m .* v(2) .* 2 .^ (-1 .* Fi(i));
		v_update(2) = v(2) + v(1) .* 2 .^ (-1 .* Fi(i));
		v_update(3) = v(3) - alphai(i);
		v(1) = v_update(1);
		v(2) = v_update(2);
		v(3) = v_update(3);
	endif
endfor

v
v_normalized = v .* K
K